<template>
  <div class="add-sales">
    <el-card>
      <div class="header" slot="header">结算页面</div>
      <div class="card-body">
        <!-- 会员卡 -->
        <div class="vid-card">
          <el-input placeholder="会员卡"></el-input>
          <el-link>张三</el-link>
        </div>
        <!-- 结算的商品添加 -->
        <el-form :rules="rules" ref="salesForm" inline>
          <el-form-item label="商品名称">
            <el-select
              @change="changeData"
              v-model="select_goods_id"
              filterable
              placeholder="请选择商品"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="单价" prop="sale_price">
            <el-input
              readonly="readonly"
              placeholder="单价"
              v-model="sale_price"
            ></el-input>
          </el-form-item>
          <el-form-item label="数量" prop="quantity">
            <el-input
              placeholder="数量"
              v-model="quantity"
              @change="changeQuantity"
            ></el-input>
          </el-form-item>
          <el-form-item label="金额" prop="subtotal">
            <el-input
              readonly="readonly"
              placeholder="金额"
              v-model="subtotal"
            ></el-input>
          </el-form-item>
          <el-button type="success" @click="addSingleGoods">添加</el-button>
        </el-form>
        <!-- 结算的商品列表 -->
        <el-table
          :data="saleGoodsDatas"
          stripe
          highlight-current-row
          :style="{ width: tableWidth + 'px' }"
        >
          <el-table-column prop="product_name" label="商品名称">
          </el-table-column>
          <el-table-column prop="product_category_name" label="商品分类">
          </el-table-column>
          <el-table-column prop="sale_price" label="商品单价">
          </el-table-column>
          <el-table-column prop="quantity" label="购买数量"> </el-table-column>
          <el-table-column prop="subtotal" label="小计金额"> </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <div class="total-price">
          <el-form
            :model="sales"
            :inline="true"
            class="demo-form-inline"
            ref="totalPriceFormData"
          >
            <el-form-item label="实收金额">
              <el-input
                @change="receiveMoney"
                placeholder="实收金额"
                v-model="sales.received_amount"
              ></el-input>
            </el-form-item>
            <el-form-item label="支付方式">
              <el-select
                v-model="sales.payment_method"
                clearable
                placeholder="请选择支付方式"
              >
                <el-option value="微信">微信</el-option>
                <el-option value="支付宝">支付宝</el-option>
                <el-option value="现金">现金</el-option>
                <el-option value="会员卡">会员卡</el-option>
              </el-select>
            </el-form-item>
            <el-divider></el-divider>
            <el-form-item>
              <el-tag>总金额：{{ sales.total_amount }}</el-tag>
            </el-form-item>
            <el-form-item>
              <el-tag>找零：{{ sales.change_amount }}</el-tag>
            </el-form-item>
            <el-form-item>
              <el-button class="total-btn" @click="submitTotalMoney"
                >结账</el-button
              >
            </el-form-item>
          </el-form>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getAllGoods } from "@/api/Goods";
import { addSalesTotal } from "@/api/sales";
export default {
  data() {
    return {
      // 商品的下拉框
      options: [],
      // 选中的商品的id
      select_goods_id: "",
      // 结算的某个商品信息
      quantity: "", // 数量
      sale_price: "", // 单价
      subtotal: "", // 小计金额

      // 表格中待计算的商品列表
      saleGoodsDatas: [],
      tableWidth: 1200,

      // 总金额
      sales: {
        // 收银员的id
        emp_id: "",
        // 总金额
        total_amount: 0,
        // 实收金额
        received_amount: 0,
        // 找零金额
        change_amount: 0,
        // 支付方式
        payment_method: "现金",
        // 备注
        remarks: 0,
        // 订单明细
        salesDetails: [],
      },
      rules: {},
      // 记录所有的商品数据
      goods: [],
      // 记录本次添加的结算某个商品信息
      markGoods: {},
    };
  },
  methods: {
    // 结账
    submitTotalMoney() {
      // 需要处理订单与明细的数据
      this.sales.emp_id = JSON.parse(localStorage.getItem("loginUser")).id;
      this.saleGoodsDatas.forEach((v) => {
        this.sales.salesDetails.push({
          product_id: v.id,
          product_name: v.product_name,
          product_category_id: v.product_category_id,
          sale_price: v.sale_price,
          quantity: v.quantity,
          subtotal: v.subtotal,
        });
      });
      addSalesTotal(this.sales).then((resp) => {
        let respData = resp.data;
        if (respData.code === 20000) {
          location.reload();
        }
      });
    },
    // 计算找零金额
    receiveMoney() {
      this.sales.change_amount = (
        this.sales.received_amount - this.sales.total_amount
      ).toFixed(2);
    },
    // 删除表格中某个商品（某一行）
    handleDelete(index, row) {
      console.log(index, row);
      this.saleGoodsDatas.splice(index, 1);
    },
    // 点击添加按钮，将单一商品的数据放到数组中
    addSingleGoods() {
      let g = this.goods.filter((v) => {
        return this.select_goods_id === v.id;
      })[0];
      this.saleGoodsDatas.push({
        ...g,
        quantity: this.quantity,
        subtotal: this.subtotal,
      });
      // 计算总金额
      let total = 0;
      this.saleGoodsDatas.forEach((v) => {
        total += Number(v.subtotal);
      });
      this.sales.total_amount = total.toFixed(2);
      // 清空数据
      this.select_goods_id = "";
      this.quantity = 0; // 数量
      this.sale_price = 0; // 单价
      this.subtotal = 0; // 小计金额
    },

    // 查询所有商品数据
    loadAllGoods() {
      getAllGoods().then((resp) => {
        let respData = resp.data;
        // 把加载的所有商品数据保存起来后续使用
        this.goods = respData.data;
        this.options = respData.data.map((v) => {
          return {
            value: v.id,
            label: v.product_name,
          };
        });
      });
    },
    // 下拉商品的数据发生改变时触发
    changeData(data) {
      this.markGoods = this.goods.filter((v) => {
        return v.id == data;
      })[0];
      // 需要给单价赋值
      this.sale_price = this.markGoods.sale_price;
    },
    // 购买数量发生改变
    changeQuantity() {
      this.subtotal = (this.sale_price * this.quantity).toFixed(2);
    },
  },

  created() {
    this.loadAllGoods();
  },
};
</script>

<style lang="less" scoped>
.add-sales {
  width: 100%;
  height: 100%;
  .vid-card {
    display: flex;
    align-items: center;
    .el-input {
      width: 360px;
      margin-right: 20px;
    }
  }
  .el-form {
    margin: 20px 0;
  }
  .el-tag {
    text-align: center;
    width: 480px;
    height: 60px;
    line-height: 60px;
    font-size: 40px;
  }
  .total-btn {
    width: 120px;
    height: 60px;
    font-size: 30px;
    background-color: #f00;
    color: #fff;
  }
}
</style>
